package com.bcx.wind.workflow.imp.cmd.runtimecmd;

import com.bcx.wind.workflow.entity.WindTask;
import com.bcx.wind.workflow.entity.WindTaskActor;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.support.Assert;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.LinkedList;
import java.util.List;

import static com.bcx.wind.workflow.message.ErrorCode.DATABASE_OPERATE_ERROR;
import static com.bcx.wind.workflow.message.ErrorCode.UPDATE_TASK_FAIL;

/**
 * 执行添加审批人命令
 *
 * @author  zhanglei
 */
public class AddTaskActorCommand implements Command<Void> {

    /**
     * 任务ID
     */
    private String taskId;

    /**
     * 审批人集合
     */
    private List<String> actors;

    public AddTaskActorCommand(String taskId,List<String> actors){
        this.taskId = taskId;
        this.actors = actors;
    }

    @Override
    public Void executor(CommandContext context) {
        if(ObjectHelper.isEmpty(this.actors)){
            return null;
        }
        checkArgs(context);
        //执行添加
        insertActor(context);
        return null;
    }

    private void insertActor(CommandContext context){
        List<WindTaskActor> windTaskActors = new LinkedList<>();
        for(String userId : actors){
            WindTaskActor windTaskActor = new WindTaskActor()
                    .setTaskId(this.taskId)
                    .setActorId(userId);
            windTaskActors.add(windTaskActor);
        }
        int ret = context.access().insertTaskActor(windTaskActors);
        if(ret != windTaskActors.size()){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
    }

    private void checkArgs(CommandContext context){
        if(taskId == null){
            WindError.error(UPDATE_TASK_FAIL,null,"taskId");
        }
        WindTask task = context.access().getTaskInstanceById(taskId);
        if(task == null){
            WindError.error(UPDATE_TASK_FAIL,null,"windTask");
        }
        checkUser();
    }


    private void checkUser(){
        for(String userId : this.actors){
            Assert.notEmptyError(UPDATE_TASK_FAIL,userId,"actorId");
        }
    }
}
